<template>
  <!--  <el-button @click="resetDateFilter">reset date filter</el-button>-->
  <!--  <el-button @click="clearFilter">reset all filters</el-button>-->
  <!--  这里是行内表单-->
  <el-form :inline="true" :model="queryParam" class="demo-form-inline">
    <el-form-item label="用户名：">
      <el-input v-model="queryParam.userName" placeholder="用户名"/>
    </el-form-item>

    <el-form-item label="昵称：">
      <el-input v-model="queryParam.nickName" placeholder="昵称"/>
    </el-form-item>

    <!--      <el-select v-model="queryParam.nickName" placeholder="Activity zone">-->
    <!--        <el-option label="Zone one" value="shanghai" />-->
    <!--        <el-option label="Zone two" value="beijing" />-->
    <!--      </el-select>-->

    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
  </el-form>
  <div class="flex">
    <!--    这里简单限制权限,indexOf如果有会返回下标，没有则会返回-1-->
    <!--    <el-button type="primary" :icon="Edit" v-if="$store.state.user.roles.indexOf('admin') !==-1" />-->
    <el-button type="primary" :icon="Plus" v-hasRole="['admin']" @click="create"/>

    <el-button type="primary" :icon="Share"/>
    <el-button type="primary" :icon="Delete"/>
    <el-button type="primary" :icon="Search">Search</el-button>
    <el-button type="primary">
      Upload
      <el-icon class="el-icon--right">
        <Upload/>
      </el-icon>
    </el-button>
  </div>
  <el-table ref="tableRef" row-key="date" :data="tableData" style="width: 100%">
    <!--    <el-table-column-->
    <!--        prop="date"-->
    <!--        label="Date"-->
    <!--        sortable-->
    <!--        width="180"-->
    <!--        column-key="date"/>-->
    <!--        :filters="[-->
    <!--        { text: '2016-05-01', value: '2016-05-01' },-->
    <!--        { text: '2016-05-02', value: '2016-05-02' },-->
    <!--        { text: '2016-05-03', value: '2016-05-03' },-->
    <!--        { text: '2016-05-04', value: '2016-05-04' },-->
    <!--      ]"-->
    <!--        :filter-method="filterHandler"-->
    <el-table-column prop="userName" label="用户名"/>
    <el-table-column prop="nickName" label="昵称"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
        >编辑
        </el-button
        >
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >Delete
        </el-button
        >
      </template>
    </el-table-column>
    <!--    <el-table-column prop="name" label="Name" width="180" />-->
    <!--    <el-table-column prop="address" label="Address" :formatter="formatter" />-->

    <!--    <el-table-column-->
    <!--        prop="tag"-->
    <!--        label="Tag"-->
    <!--        width="100">-->
    <!--&lt;!&ndash;        :filters="[&ndash;&gt;-->
    <!--&lt;!&ndash;        { text: 'Home', value: 'Home' },&ndash;&gt;-->
    <!--&lt;!&ndash;        { text: 'Office', value: 'Office' },&ndash;&gt;-->
    <!--&lt;!&ndash;      ]"&ndash;&gt;-->
    <!--&lt;!&ndash;        :filter-method="filterTag"&ndash;&gt;-->
    <!--&lt;!&ndash;        filter-placement="bottom-end"&ndash;&gt;-->

    <!--      <template #default="scope">-->
    <!--        <el-tag-->
    <!--            :type="scope.row.tag === 'Home' ? '' : 'success'"-->
    <!--            disable-transitions-->
    <!--        >{{ scope.row.tag }}</el-tag-->
    <!--        >-->
    <!--      </template>-->
    <!--    </el-table-column>-->
  </el-table>
  <el-pagination background layout="prev ,pager, next" :total="total" :page-size="queryParam.size"
                 @current-change="changePage">

  </el-pagination>

  <!-- 新增和修改用户 -->
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="30%"
      align-center
  >
    <el-form :ref="userFormRef" :model="userForm" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="userForm.userName"/>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="userForm.nickName"/>
      </el-form-item>
      <el-form-item label="密码" v-if="userForm.userId === null">
        <el-input v-model="userForm.password"/>
      </el-form-item>
      <el-form-item label="确认密码" v-if="userForm.userId === null">
        <el-input v-model="userForm.confirmPassword"/>
      </el-form-item>
    </el-form>


    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFrom">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref} from 'vue'
import {ElTable} from 'element-plus'
import {listUser, add, getById, update, deleteUser} from '@/api/user'
import {Plus, Delete, Edit, Search, Share, Upload} from '@element-plus/icons-vue'

import {ElMessage, ElMessageBox} from 'element-plus'

//这里调用该路由接口在mounted里面调用会更好，而在组合式里面写，通过官网查询需要导入下面的
import {onMounted} from 'vue'

let dialogVisible = ref(false);

const tableData = ref([]);

const total = ref(0);
// const pageSize = ref(0);
//主键加载完成后调用
// onMounted(()=>{
//   listUser({page:0,size:2}).then(res =>{
//     console.log("这里是分页模块的res请求"+ res.data)
//     tableData.value=res.data.content;
//     total.value = res.data.totalElements;
//     //这里使用totalPages会发现分页显示的页数会出错，初步我认为它返回的是每一次查询该次查询返回的条数，因此size才是返回的总页数
//     pageSize.value = res.data.size;
//   })
// })
//
// const changePage = async function (current){
//     let res = await listUser({page:current-1,size:2})
//     console.log("这里是分页模块的res请求"+ res.data)
//     tableData.value=res.data.content;
//     // total.value = res.data.totalElements;
//     // pageSize.value = res.data.totalPages;
//
// }


//这里方法依旧过于累赘，这里进一步更新
// const page = ref(0);
// const pageSize = ref(2);
const queryParam = ref({

  size: 2,
  page: 0,
  userName: "",
  nickName: "",
})

let userForm = ref({
  userId: null,
  userName: '',
  nickName: '',
  password: '',
  confirmPassword: ''

})

let title = ref("")

const getList = function () {
  listUser(queryParam.value).then(res => {
    console.log("这里是分页模块的res请求" + res.data)
    tableData.value = res.data.content;
    total.value = res.data.totalElements;
    //这里使用totalPages会发现分页显示的页数会出错，初步我认为它返回的是每一次查询该次查询返回的条数，因此size才是返回的总页数
    queryParam.value.size = res.data.size;
  })
}

onMounted(() => {
  getList();
})

const changePage = async function (current) {
  queryParam.value.page = current - 1;
  getList();
}

const onSubmit = function () {
  getList()
}

let create = function () {
  //清理数据
  userForm.value = {
    userId: null,
    userName: '',
    nickName: '',
    password: '',
    confirmPassword: ''
  }
  title.value = "新增加用户";
  dialogVisible.value = true;
}


const submitFrom = function () {

  //发送前应当有几步需要处理
  //1、对比确认密码和密码

  //2、校验表单，比如规范等


  //3、提交ajax请求
  //后端没有这个属性，这个属性单纯前端校验用，所以这里使用delete在发送前删除这个
  delete userForm.value.confirmPassword

  //发送前判断当前的usrId是不是null，如果是null，就新增，反之则修改
  if (userForm.value.userId === null) {
    //提交ajax请求
    add(userForm.value).then(res => {
      console.log(res)

      dialogVisible.value = false;

    });
    getList();
  } else {
    update(userForm.value).then((res) => {
      console.log(res);
      if (res.status === 200) {
        dialogVisible.value = false;
      }
      //完成后要更新列表
      getList();
    })
  }


}


//测试可以看出index是行数，row是一个代理对象，可以返回该点击对象信息
const handleEdit = function (index, row) {
  console.log(index);
  console.log("----")
  console.log(row);
  getById(row.userId).then(res => {
    userForm.value = res.data;
    //打开修改窗口
    this.title = "修改用户";
    dialogVisible.value = true;
  })
}


const handleDelete = function (index, row) {

  ElMessageBox.alert('您确定要删除此条信息吗？', '提示', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确定',
    callback: () => {
      deleteUser(row.userId).then(res => {
        if (res.status === 200) {
          // alert("删除成功")
          getList();
          ElMessage({
            type: 'info',
            message: '删除成功',
          });
        }
      });
    },
  });
};
//  tableData= ref([
//   {
//     date: '2016-05-03',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//     tag: 'Home',
//   },
//   {
//     date: '2016-05-02',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//     tag: 'Office',
//   },
//   {
//     date: '2016-05-04',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//     tag: 'Home',
//   },
//   {
//     date: '2016-05-01',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//     tag: 'Office',
//   },
// ])

// export default {
//   name: "index"
// }
</script>

<style scoped>

</style>